import { Event } from "socket.io";
import { RequestMethod } from "../src/lib/defines";
import { Classrooms } from '../src/lib/Classrooms'
import { errorMsg } from "../src/utils/socket_message";
import {getLogger} from "log4js";
import {stringify} from "../src/utils/utils";


const logger = getLogger('Offer Helper');

export async function offerErrorMiddleware (app, io?) {
  const { socket } = app.locals;
  const { userId, username } = socket.handshake.query;
  const owner = { userId, username }
  const offerError = (message) => errorMsg(RequestMethod.offer, message, { owner })
  /**
   * 用户登录时
   * 查询未读通知，全部推送给对方。
   */
  socket.use(async (event: Event, next: (err?: Error) => void) => {
    const [name, params, cb] = event

    if (name === RequestMethod.offer) {
      const { member, room } = params
      logger.info(`params:(${username}) => `, stringify(params))

      if (!room) {
        /**
         * ** 房间不存在 **
         *
         * 参数 room 必须传入
         */
        return cb && cb(offerError(`params: room ${ JSON.stringify(room, null, 2) } must required!`))
      }

      if (!member) {
        /**
         * ** 成员不存在 **
         *
         * 参数 member 必须传入
         */
        return cb && cb(offerError(`params: member ${ JSON.stringify(member, null, 2) } must required!`))
      }

      const classroom = Classrooms.get(room.classId)
      if (!classroom) {
        /**
         * ** 房间没找到 **
         *
         * 房间需要在 Classrooms Map 中能够找到
         */
        return cb && cb(offerError(`room: ${ JSON.stringify(room, null, 2) } not found in rooms!`))
      }

      const __member = classroom.getMember(member.userId);
      if (!__member) {
        /**
         * ** 房间中的成员不存在 **
         *
         * 成员在房间找不到
         */
        return cb && cb(offerError(`member: ${ JSON.stringify(member, null, 2) } not found in room!`))
      }
    }

    next()
  })

}
